<script setup lang="ts">
import { computed, onUnmounted, reactive, ref, shallowRef, toRefs, watch, onMounted } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { useDeviceListApi } from '@/api/gps/device'
import { cloneDeep } from 'lodash'
import MaOrgSelect from '@/components/ma-org/ma-org-select/index.vue'
import { computeSubTitle } from '@/utils/gps/format'
import { getNodeTypeIcon } from '@/utils/gps/device'
import FullDetail from '@/views/dashboard/left/trackInfo/fullDetail.vue'
import StopDetail from '@/views/dashboard/left/trackInfo/stopDetail.vue'
import TripDetail from '@/views/dashboard/left/trackInfo/tripDetail.vue'
import { useGetDeviceMileageDrivenApi, useGetTrackPosApi } from '@/api/gps/gps'
import moment from 'moment'
import type { CalendarDateType, CalendarInstance } from 'element-plus'
import { ElButton, ElDatePicker, ElMessage } from 'element-plus'
import type { Component, ShallowRef } from 'vue'
import { gpsbus, trackBus } from '@/utils/gps/event'
import UrgentDetail from '@/views/dashboard/left/trackInfo/urgentDetail.vue'

type PageName = 'all' | 'trip' | 'stop' | 'urgent'
const userStore = useUserStore()

const queryForm = reactive({
  // deptId: userStore.user.orgId || 1,
  orderField: 'signal_update_time',
  order: 'DESC',
  pageNum: 1,
  pageSize: 1000,
  keyWords: ''
})
const calendar = ref<CalendarInstance>()
const deviceList = ref<any[]>([])
const activeName = ref<PageName>('all')
const currentComponent = shallowRef(FullDetail)
const mode = ref<'calendar' | 'time'>('calendar')
const loading = ref(false)
const mileageDrivenList = ref<{ [key: string]: string }>()
const recordData = reactive({
  stops: [],
  trips: [],
  alarms: []
})

const deviceForm = reactive({
  imei: '',
  dateTime: new Date(),
  startTime: moment().subtract(1, 'hours').format('YYYY-MM-DD HH:mm:ss'),
  endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
  stopTime: 3,
  shortcut: 1
})

const componentsList = reactive<{ [name: PageName]: ShallowRef<Component> }>({
  all: shallowRef(FullDetail),
  trip: shallowRef(TripDetail),
  stop: shallowRef(StopDetail),
  urgent: shallowRef(UrgentDetail)
})

watch(
  () => deviceForm.dateTime,
  () => {
    if (!deviceForm.imei) {
      return
    }
    const currentDate = moment(deviceForm.dateTime as Date)
    requestTrack(deviceForm.imei, currentDate.format('YYYY-MM-DD 00:00:00'), currentDate.format('YYYY-MM-DD 23:59:59'))
  }
)
watch(
  () => mode.value,
  (value) => {
    if (value === 'calendar') {
      deviceChange(deviceForm.imei)
    }
  }
)

onMounted(() => {
  gpsbus.on('trackListInit', initData)
})
onUnmounted(() => {
  gpsbus.off('trackListInit')
})

/**
 * 获取记录
 * @param imei
 * @param start
 * @param end
 */
async function requestTrack(imei: string, start: string, end: string) {
  if (!imei) {
    return ElMessage.info('必须选择一个设备！')
  }
  const { data } = await useGetTrackPosApi({
    imei: imei,
    startTime: start,
    endTime: end,
    withStop: true,
    withPos: true,
    withTrip: true,
    withAlarm: true
  })
  trackBus.emit('track_init', data)
  const { stops, trips, alarms } = data
  recordData.stops = stops || []
  recordData.trips = trips || []
  recordData.alarms = alarms || []
}

const todayMile = computed(() => {
  const dev = deviceList.value.find((item) => item.imei === deviceForm.imei)
  if (!dev) {
    return 0
  }
  return dev.todayDistance
})

function initData(imei: string) {
  queryForm.keyWords = imei
  useDeviceListApi(cloneDeep(queryForm)).then((res) => {
    deviceList.value = res.data.list
    deviceForm.imei = imei
    deviceChange(imei)
  })
  // setTimeout(() => {
  //   deviceChange(imei)
  // }, 500)
}

// /**
//  * 获取设备列表
//  */
// function getDeviceList() {
//   useDeviceListApi(cloneDeep(queryForm)).then((res) => {
//     deviceList.value = res.data.list
//   })
// }

/**
 * 远程搜索
 */
function remoteMethod(val: string) {
  if (val) {
    loading.value = true
    queryForm.keyWords = val
    useDeviceListApi(cloneDeep(queryForm)).then((res) => {
      deviceList.value = res.data.list
      loading.value = false
    })
  } else {
    deviceList.value = []
  }
}

/**
 * 查询设备某月各天行驶里程统计
 * @param dateRange
 */
function getDeviceMonthMileageDriven(dateRange: string[]) {
  useGetDeviceMileageDrivenApi({
    imei: deviceForm.imei,
    startTime: dateRange[0],
    endTime: dateRange[1]
  }).then((res) => {
    mileageDrivenList.value = createCalendarMileageArr(res.data)
    // console.log(mileageDrivenList.value)
  })
}

/**
 * 计算某年某月首尾日期
 * @param time
 */
function startAndEndMonthDay(time: Date) {
  const currenDate = moment(time)
  return [
    currenDate.startOf('month').format('YYYY-MM-DD HH:mm:ss'),
    currenDate.endOf('month').format('YYYY-MM-DD 23:59:59')
  ]
}

/**
 * 创建一个符合日历表天数1:1的日期映射表 {日期：值}
 * @param data
 */
function createCalendarMileageArr(data: { startDistance: number; endDistance: number; createTime: string }[]) {
  let monthData = {}
  const today = moment().format('YYYY-MM-DD')
  data.forEach((item) => {
    const day = item.createTime.slice(0, 10)
    if (today === day) {
      monthData[day] = Math.ceil(todayMile.value / 1000)
    } else {
      monthData[day] = Math.ceil((item.endDistance - item.startDistance) / 1000)
    }
  })
  return monthData
}

/**
 * 设备选中的回调
 */
function deviceChange(val) {
  if (val === undefined) {
    return
  }
  if (mode.value === 'time') {
    return
  }
  if (!deviceForm.imei) {
    return ElMessage.info('必须选择一个设备！')
  }
  getDeviceMonthMileageDriven(startAndEndMonthDay(new Date()))
  deviceForm.dateTime = new Date()
}

/**
 * 日期控件事件
 * @param val
 */
function selectDate(val: CalendarDateType) {
  calendar.value?.selectDate(val)
  getDeviceMonthMileageDriven(startAndEndMonthDay(deviceForm.dateTime))
}

/**
 * 模式切换
 */
function modeChange(val) {
  console.log(val)
}

function shortcutChange(val: number) {
  deviceForm.startTime = moment().subtract(val, 'hours').format('YYYY-MM-DD HH:mm:ss')
  deviceForm.endTime = moment().format('YYYY-MM-DD HH:mm:ss')
}

function query() {
  // trackStore.requestTrack(deviceForm.imei, deviceForm.startTime, deviceForm.endTime)
  requestTrack(deviceForm.imei, deviceForm.startTime, deviceForm.endTime)
}

function tabChange(val) {
  currentComponent.value = componentsList[val]
}

defineExpose({
  initData
})
</script>

<template>
  <div style="height: calc(100% - 54px); display: flex; flex-direction: column">
    <div class="search">
      <!--      <ma-org-select v-model="queryForm.deptId" authority placeholder="请选择" @change="getDeviceList"></ma-org-select>-->
      <el-radio-group v-model="mode" class="mode_select" @change="modeChange">
        <el-radio-button label="日历" value="calendar" />
        <el-radio-button label="时间" value="time" />
      </el-radio-group>
      <el-select
        v-model="deviceForm.imei"
        filterable
        remote
        reserve-keyword
        :loading="loading"
        :remote-method="remoteMethod"
        placeholder="搜索"
        class="margin-l"
        @change="deviceChange">
        <el-option v-for="item in deviceList" :key="item.imei" :label="item.plateNo" :value="item.imei">
          <i class="zTree_icon" :style="getNodeTypeIcon(item.connectionStatus, item.type)"></i>
          <span>{{ item.plateNo }}</span>
          <span style="margin-left: 15px">{{ computeSubTitle(item) }}</span>
        </el-option>
      </el-select>
    </div>

    <el-calendar v-show="mode === 'calendar'" ref="calendar" v-model="deviceForm.dateTime" class="calendar">
      <template #header="{ date }">
        <span>{{ date }}</span>
        <el-button-group>
          <el-button size="small" @click="selectDate('prev-month')">上个月</el-button>
          <el-button size="small" @click="selectDate('today')">今天</el-button>
          <el-button size="small" @click="selectDate('next-month')">下个月</el-button>
        </el-button-group>
      </template>
      <template #date-cell="{ data }">
        <p>{{ data.day.slice(8, 10) }}</p>
        <p v-if="!data.isSelected">
          {{
            mileageDrivenList?.[data.day.slice(0, 10)] === undefined ? '-' : mileageDrivenList?.[data.day.slice(0, 10)]
          }}
        </p>
        <p :class="data.isSelected ? 'is-selected' : ''">
          {{ data.isSelected ? '✔️' : '' }}
        </p>
      </template>
    </el-calendar>
    <el-form v-show="mode === 'time'" v-model="deviceForm" class="form_query">
      <el-form-item label="开始日期" prop="startTime">
        <el-date-picker
          v-model="deviceForm.startTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="开始日期" />
      </el-form-item>
      <el-form-item label="结束日期" prop="endTime">
        <el-date-picker
          v-model="deviceForm.endTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="停留时长" class="display_column">
        <el-radio-group v-model="deviceForm.stopTime" class="margin-r">
          <el-radio :value="3" size="small" border>3分钟</el-radio>
          <el-radio :value="5" size="small" border>5分钟</el-radio>
          <el-radio :value="10" size="small" border>10分钟</el-radio>
          <el-radio :value="30" size="small" border>30分钟</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="快捷时间" class="display_column">
        <el-radio-group v-model="deviceForm.shortcut" class="margin-r" @change="shortcutChange">
          <el-radio :value="1" size="small" border>1小时</el-radio>
          <el-radio :value="6" size="small" border>6小时</el-radio>
          <el-radio :value="12" size="small" border>12小时</el-radio>
          <el-radio :value="24" size="small" border>1天</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-button style="margin-left: 50%; transform: translateX(-50%); width: 100px" round type="primary" @click="query"
        >查询</el-button
      >
    </el-form>
    <el-tabs v-model="activeName" tab-position="top" class="demo-tabs" @tab-change="tabChange">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="行程" name="trip"></el-tab-pane>
      <el-tab-pane label="停留点" name="stop"></el-tab-pane>
      <el-tab-pane label="报警" name="urgent"></el-tab-pane>
    </el-tabs>
    <el-scrollbar>
      <component :is="currentComponent" :record-data="recordData"></component>
    </el-scrollbar>
  </div>
</template>

<style scoped>
.search {
  display: flex;
}
.search .mode_select {
  width: 120px;
}
.margin-l {
  flex: 1;
  margin-left: 15px;
}
.margin-r > label {
  margin-right: 8px;
}
.zTree_icon {
  margin-right: 2px;
  vertical-align: center;
  line-height: 0;
  width: 16px;
  height: 16px;
  display: inline-block;
  border: 0 none;
  cursor: pointer;
  outline: none;
  transform: translateY(2px);
}
.form_query {
  margin-top: 12px;
}
.calendar {
  width: 330px;
}
>>> .calendar .el-calendar__body {
  padding: 10px 12px 0;
}
.display_column {
  flex-direction: column;
}
>>> .display_column > label {
  justify-content: flex-start;
}
</style>
